import os
import re


def find_root_project(current_path):
    """
    递归查找父目录，直到找到包含 "root_project" 文件的目录。
    :param current_path: 当前路径
    :return: 包含 "root_project" 文件的目录路径，如果找不到则返回 None
    """
    # 获取当前目录中的文件列表
    files = os.listdir(current_path)
    # 检查是否有名为 "root_project" 的文件
    if "__root_project__" in files:
        # 如果找到了，返回当前路径
        return current_path
    else:
        # 如果当前目录没有 "root_project" 文件，则继续向上查找父目录
        parent_path = os.path.dirname(current_path)
        # 如果已经到达根目录，即 parent_path 与 current_path 相同，则返回 None
        if parent_path == current_path:
            return None
        # 否则，继续在父目录中查找
        else:
            return find_root_project(parent_path)


# project_root_path = find_root_project(os.path.dirname(__file__))
# print(project_root_path)


# def get_file_path(file):
#     return my_path_join(project_root_path, file)


def my_path_join(*paths):
    # 将所有路径连接起来
    joined_path = os.path.join(*paths)

    # 检查最后一个路径是否是文件
    if os.path.splitext(paths[-1])[1]:  # 如果最后一个路径有扩展名，即为文件
        dir_path = os.path.dirname(joined_path)  # 获取上一层文件夹路径
    else:
        dir_path = joined_path  # 如果最后一个路径不是文件，直接使用连接后的路径

    # 创建文件夹（如果需要）
    os.makedirs(dir_path, exist_ok=True)

    return joined_path


def get_native_project_file_path():
    native_path = os.getenv("NATIVE_PATH")
    return my_path_join(native_path)


def replace_path_prefix_to_native_path(full_path):
    return replace_path_prefix(full_path, get_native_project_file_path())


def replace_path_prefix(full_path, prefix_path):
    # Normalize paths to use forward slashes
    full_path = full_path.replace('\\', '/')
    prefix_path = prefix_path.replace('\\', '/')

    # Remove multiple consecutive slashes
    full_path = re.sub(r'/+', '/', full_path)
    prefix_path = re.sub(r'/+', '/', prefix_path)

    if full_path.startswith(prefix_path):
        # Remove the prefix_path and replace with '/native_files/'
        new_path = full_path.replace(prefix_path, '/native_files/', 1)
        # Remove any remaining multiple consecutive slashes
        new_path = re.sub(r'/+', '/', new_path)
        return new_path
    else:
        raise ValueError("The full path does not start with the specified prefix path.")
